<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="家长id" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入家长id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="校区名称" prop="campusName">
        <el-input
          v-model="queryParams.campusId"
          placeholder="请输入校区id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="家长名称" prop="parentName">
        <el-input
          v-model="queryParams.parentName"
          placeholder="请输入家长名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="家长称呼" prop="parentRelation">
        <el-input
          v-model="queryParams.parentRelation"
          placeholder="请输入家长称呼(母亲/父亲.....)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:courseParent:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:courseParent:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:courseParent:remove']"
        >删除</el-button>
      </el-col>
       <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:courseParent:edit']"
        >绑定孩子</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['course:courseParent:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseParentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="家长id" align="center" prop="parentId" width="100"/>
      <el-table-column label="校区名字" align="center" prop="campusName"  width="100"/>
      <el-table-column label="家长名称" align="center" prop="parentName"  width="100"/>
      <el-table-column label="家长称呼" align="center" prop="parentRelation"  width="100"/>
      <el-table-column label="图片路径" align="center" prop="parentUrl"  width="200">
        <template slot-scope="scope">
          <div class="table-image-container">
            <el-image :src="scope.row.parentUrl" alt="商品图片" class="table-image" @error="handleImageError(scope.row)"
              :preview-src-list="[scope.row.parentUrl]" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="parentPh"  width="160"/>
      <el-table-column label="住址" align="center" prop="parentAddr"  width="250"/>
      <el-table-column label="微信号" align="center" prop="parentWechat"  width="110"/>
      <el-table-column label="绑定学生" align="center" prop="stuList"  width="200">
        <template slot-scope="scope">
            <div>
              <span v-for="stu in scope.row.courseStus" :key="stu.stuId">
                {{ stu.stuName }}
              </span>
            </div>
        </template>
      </el-table-column>
    
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:courseParent:edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:courseParent:remove']"
          >删除</el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handlebind(scope.row)"
          >绑定</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 绑定学生对话框 -->
    <el-dialog :title="title" :visible.sync="openBind" width="1000px" append-to-body>
          <div style="width: 80%; margin-left: 100px;">
             <el-transfer
              style="text-align: left; display: inline-block"
              v-model="value"
              filterable
              :left-default-checked="[2, 3]"
              :right-default-checked="[1]"
              :render-content="renderFunc"
              :titles="['未绑定学生', '您绑定的学生']"
              :button-texts="['解绑','绑定']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              @change="handleChange"
              :data="bindStuData">
            </el-transfer>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="comfirmBind(value)">确 定</el-button>
            <el-button @click="openBind =false">取 消</el-button>
          </div>
 
    </el-dialog>
    <!-- 添加或修改家长管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="校区名称" prop="campusId">
           <el-select v-model="form.campusId" placeholder="请选择校区名称">
            <el-option
              v-for="campus in campusInfoList"
            
              :key="campus.campusId"
              :label="campus.campusName"
              :value="campus.campusId"
            >
          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="家长名称" prop="parentName">
          <el-input v-model="form.parentName" placeholder="请输入家长名称" />
        </el-form-item>
        <el-form-item label="家长称呼" prop="parentRelation">
          <el-input v-model="form.parentRelation" placeholder="请输入家长称呼(母亲/父亲.....)" />
        </el-form-item>
        <el-form-item label="家长图片" prop="parentUrl">
          <el-upload class="upload-demo" drag action :multiple="false" :http-request="uploadImg"
          :show-file-list="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>

          <!-- 图片预览区域 -->
          <div v-if="form.parentUrl" class="image-preview">
            <img :src="form.parentUrl" alt="预览图" class="preview-image">
          </div>
        </el-form-item>

       
        <el-form-item label="联系方式" prop="parentPh">
          <el-input v-model="form.parentPh" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="住址" prop="parentAddr">
          <el-input v-model="form.parentAddr" placeholder="请输入住址" />
        </el-form-item>
        <el-form-item label="微信号" prop="parentWechat">
          <el-input v-model="form.parentWechat" placeholder="请输入微信号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCourseParent, getCourseParent, delCourseParent, addCourseParent, updateCourseParent,listAllCampus,getStuByCampusId,batchBind } from "@/api/course/courseParent"
import { uploadIdCard } from "@/api/artGood/artGood"

export default {
  name: "CourseParent",
  data() {
    return {
      parentId: null,
      value: [1, 3],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 家长管理表格数据
      courseParentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示绑定学生弹出层
      openBind: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        campusId: null,
        parentName: null,
        parentRelation: null,
      },
      
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        campusId: [
          { required: true, message: "校区id不能为空", trigger: "blur" }
        ],
      },
      campusInfoList: [],
      options: [
      ],
      bindStuData:[
        {
          key: 1,
          label: '张三',
        },
       
     ],
    renderFunc(h, option) {
        return <span>{ option.label }</span>;
    }
    }
  },
  created() {
    this.getList()
    this.getCampusListInfo()
  },
  methods: {
    //确认绑定
    async comfirmBind(value){
      if(value.length==0){
        value = []
      }
      await batchBind({parentId:this.parentId,stuIds:value})
      this.getList()
      this.openBind = false
      
    },
    //穿梭框监听事件
    handleChange(value, direction, movedKeys){
         console.log(value);
    },
    // 处理图片加载错误
    handleImageError(row) {
      console.log('图片加载失败:', row);
      // 可以在这里设置默认图片
      // row.goodPicture = '/default-image.jpg';
    },
    /** 查询家长管理列表 */
    getList() {
      this.loading = true
      listCourseParent(this.queryParams).then(response => {
        this.courseParentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        parentId: null,
        campusId: null,
        parentName: null,
        parentRelation: null,
        parentUrl: null,
        parentPh: null,
        parentAddr: null,
        parentWechat: null,
        parentCreTime: null,
        parentUpdTime: null,

        empty1: null,
        empty2: null,
        empty3: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.parentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加家长管理"
    },
    /** 根据campusId查询该校区还未绑定的学生 */
   async selectStuByCampusId(campusId) {
      try {
        const response = await getStuByCampusId(campusId);
        console.log("API响应数据:", response);
        
        this.options = response.courseStus.map(item => ({
          key: item.stuId,
          label: item.stuName,
          parentId: item.parentId
        }));
        
        console.log("处理后的options:", this.options);
        return this.options; // 返回处理后的数据以便链式调用
      } catch (error) {
        console.error("获取学生数据失败:", error);
        throw error; // 抛出错误以便外部捕获
      }
    },
    /** 修改按钮操作 */
   handleUpdate(row) {
      this.selectStuByCampusId(row.campusId)

      this.reset()
      const parentId = row.parentId || this.ids
      getCourseParent(parentId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改家长管理"
      })
    },
    //绑定按钮操作
    async handlebind(row) {
      try {
        //获取当前家长的id
        this.parentId = row.parentId
        console.log(this.parentId,"当前家长Id")
        // 等待学生数据加载完成
        await this.selectStuByCampusId(row.campusId);
        
        // 处理已绑定学生
        console.log(this.value)
        this.value = row.courseStus.map(item => Number(item.stuId));
        console.log("已绑定学生ID:", this.value);
        
        // 过滤未绑定学生（parentId为空且不在已绑定列表中）
        console.log(this.options)
        this.bindStuData = this.options.filter(item => 
          !item.parentId || this.value.includes(item.key) 
        );
        console.log("未绑定学生:", this.bindStuData)
        this.openBind = true;
        this.title = "绑定学生管理";
      } catch (error) {
        console.error("绑定操作失败:", error);
        this.$message.error("加载学生数据失败");
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.parentId != null) {
            updateCourseParent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addCourseParent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const parentIds = row.parentId || this.ids
      this.$modal.confirm('是否确认删除家长管理编号为"' + parentIds + '"的数据项？').then(function() {
        return delCourseParent(parentIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('course/courseParent/export', {
        ...this.queryParams
      }, `courseParent_${new Date().getTime()}.xlsx`)
    },
    getCampusListInfo(){
      console.log("1")
      listAllCampus().then(response => {
        // this.courseParentList = response.rows
        // this.total = response.total
        // this.loading = false
        this.campusInfoList = response.data
        // for (const element of this.campusInfoList) {
        //   element.campusId = element.campusId.toString()
        // }
        
        // console.log(response)
      })
    },
      uploadImg(item) {
      const formData = new FormData();
      formData.append("file", item.file);

      uploadIdCard(formData)
        .then(res => {
          this.$modal.msgSuccess("上传成功");
          // 直接赋值给表单的goodPicture字段
          this.form.parentUrl = res.data.file.url;
          console.log('图片URL已保存到表单:', this.form.parentUrl);

          // 可选：上传成功后显示预览
          this.previewImage = res.data.file.url;
        })
        .catch(error => {
          this.$modal.msgError("上传失败: " + error.message);
          console.error('图片上传失败:', error);
        });
    },
  }
}
</script>
<style scoped>
  /* 预览图 */
  .preview-image {
    height: 100px;
    width: 100px;
  }
  .table-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  }
  .table-image {
  max-width: 80px;
  max-height: 80px;
  border-radius: 4px;
  object-fit: cover;
  border: 1px solid #ebeef5;
  }
</style>
